export interface TopicElement {
  id: string;
  type: 'text' | 'image';
  content: string; // 文本内容或图片路径
}

export interface Topic {
  id: string;
  userId: string;
  title: string;
  elements: TopicElement[];
  createTime: number;
  ratings: {
    userId: string;
    rank: number; // 1-5 的排名
  }[];
  averageRank: number; // 平均排名
}

class TopicModel {
  private topics: Topic[] = [];

  async loadTopics(): Promise<void> {
    const StorageUtil = await import('../utils/StorageUtil');
    const topicsData = await StorageUtil.default.get('topics');
    this.topics = topicsData || [];
  }

  async saveTopics(): Promise<void> {
    const StorageUtil = await import('../utils/StorageUtil');
    await StorageUtil.default.set('topics', this.topics);
  }

  async createTopic(userId: string, title: string, elements: TopicElement[]): Promise<Topic> {
    await this.loadTopics();

    const newTopic: Topic = {
      id: Date.now().toString(),
      userId,
      title,
      elements,
      createTime: Date.now(),
      ratings: [],
      averageRank: 0
    };

    this.topics.unshift(newTopic); // 新话题放在前面
    await this.saveTopics();

    return newTopic;
  }

  async getAllTopics(): Promise<Topic[]> {
    await this.loadTopics();
    return this.topics;
  }

  async getTopicById(id: string): Promise<Topic | undefined> {
    await this.loadTopics();
    return this.topics.find(topic => topic.id === id);
  }

  async rateTopic(userId: string, topicId: string, rank: number): Promise<boolean> {
    await this.loadTopics();

    const topic = this.topics.find(topic => topic.id === topicId);
    if (!topic) return false;

    // 查找用户是否已经评分
    const existingRatingIndex = topic.ratings.findIndex(rating => rating.userId === userId);

    if (existingRatingIndex >= 0) {
      // 更新评分
      topic.ratings[existingRatingIndex].rank = rank;
    } else {
      // 添加新评分
      topic.ratings.push({ userId, rank });
    }

    // 重新计算平均排名
    topic.averageRank = topic.ratings.reduce((sum, rating) => sum + rating.rank, 0) / topic.ratings.length;

    await this.saveTopics();
    return true;
  }
}

export default new TopicModel();